package com.cyj.dream.admin.persistence.manager.systems;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyj.dream.admin.contacts.enums.IsDeleteEnum;
import com.cyj.dream.admin.contacts.enums.UserGolEnum;
import com.cyj.dream.core.constant.users.UserContext;
import com.cyj.dream.core.constant.users.UserInfoDTO;
import com.cyj.dream.admin.model.request.SysUserQueryRequest;
import com.cyj.dream.admin.model.system.SysUser;
import com.cyj.dream.admin.model.system.SysUserRole;
import com.cyj.dream.admin.persistence.service.ITbSysUserService;
import com.cyj.dream.admin.service.system.SysUserRoleService;
import com.cyj.dream.admin.util.IsEmptyUtils;
import com.cyj.dream.core.constant.enums.ResultCode;
import com.cyj.dream.core.exception.BizException;
import com.cyj.dream.core.util.date.AgeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description: 系统用户管理器类
 * @BelongsProject: dream-DreamChardonnay
 * @BelongsPackage: com.dream.DreamChardonnay.persistence.manager
 * @Author: ChenYongJia
 * @CreateTime: 2021-04-13 09:26
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
@Component
public class SysUserManager {

    @Autowired
    private ITbSysUserService iTbSysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 查询用户信息列表
     *
     * @param page         数据
     * @param queryRequest 请求入参参数
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.dream.DreamChardonnay.model.vo.SysUserVo>
     * @date 2021/4/17 10:54
     * @author ChenYongJia
     * @version 1.0
     */
    public Page<SysUser> list(Page<SysUser> page, SysUserQueryRequest queryRequest) {
        log.info("进入 SysUserManager 查询用户信息列表，参数 page：{}，参数 param：{}", JSONObject.toJSONString(page), queryRequest);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if (!IsEmptyUtils.isEmpty(queryRequest)) {
            // 用户地址
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserAddress())) {
                wrapper.like(SysUser::getSysUserAddress, queryRequest.getSysUserAddress());
            }
            // 用户邮箱
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserEmail())) {
                wrapper.like(SysUser::getSysUserAddress, queryRequest.getSysUserEmail());
            }
            // 生日
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserBirthday())) {
                wrapper.eq(SysUser::getSysUserBirthday, queryRequest.getSysUserBirthday());
            }
            // 用户名称
            if (!IsEmptyUtils.isEmpty(queryRequest.getUsername())) {
                wrapper.like(SysUser::getUsername, queryRequest.getUsername());
            }
            // 用户是否锁定
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserIsLock())) {
                wrapper.eq(SysUser::getSysUserIsLock, queryRequest.getSysUserIsLock());
            }
            // 用户手机号
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserPhone())) {
                wrapper.like(SysUser::getSysUserPhone, queryRequest.getSysUserPhone());
            }
            // 用户性别
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserSex())) {
                wrapper.eq(SysUser::getSysUserSex, queryRequest.getSysUserSex());
            }
            // 部门
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserInfoDepartmentId())) {
                wrapper.in(SysUser::getSysUserInfoDepartmentId, queryRequest.getSysUserInfoDepartmentId());
            }
        }

        wrapper.eq(SysUser::getDelFlag, IsDeleteEnum.DIS_DELETE.getCode());
        wrapper.orderByDesc(true, SysUser::getCreateTime);

        return iTbSysUserService.page(page, wrapper);
    }

    /**
     * 添加用户信息
     *
     * @param sysUser 用户对象
     * @return boolean
     * @date 2021/4/21 9:27
     * @author ChenYongJia
     * @version 1.0
     */
    public boolean addUserInfo(SysUser sysUser) {
        log.info("进入 SysUserManager 添加用户信息，参数 sysUser：{}", JSONObject.toJSONString(sysUser));

        try {
            UserInfoDTO userInfoDTO = UserContext.get();
            if (!IsEmptyUtils.isEmpty(this.selectByUserName(sysUser.getUsername()))) {
                log.error("用户名已存在，请重新填写表单后提交");
                throw new BizException(ResultCode.USER_HAS_EXISTED);
            }

            // 后台自动计算年龄
            if (!IsEmptyUtils.isEmpty(sysUser.getSysUserBirthday())) {
                sysUser.setSysUserAge(AgeUtils.getCurrentAge(sysUser.getSysUserBirthday()));
            }

            sysUser.setUserPassword("dream123456");
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encodedPassword = passwordEncoder.encode(sysUser.getUserPassword().trim());
            sysUser.setUserPassword(encodedPassword);
            // 计算年龄
            int age = AgeUtils.getCurrentAge(sysUser.getSysUserBirthday());
            sysUser.setSysUserAge(age);
            sysUser.setCreateTime(LocalDateTime.now());
            sysUser.setCreateUserId(userInfoDTO.getSysUserId());
            return iTbSysUserService.save(sysUser);
        } catch (Exception e) {
            log.error("调用修改用户相关信息管理器方法失败");
            throw new BizException(ResultCode.USER_TOKEN_IS_INVALID);
        }
    }

    /**
     * 查询系统所有用户信息
     *
     * @return java.util.List<com.dream.DreamChardonnay.model.system.SysUser>
     * @date 2021/6/17 10:24
     * @author ChenYongJia
     * @version 1.0
     */
    public List<SysUser> findAll(){
        log.info("进入 SysUserManager 查询系统所有用户信息");
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();

        wrapper.orderByDesc(true, SysUser::getCreateTime);
        return iTbSysUserService.list(wrapper);
    }

    /**
     * 逻辑删除用户信息
     *
     * @param sysUser 用户对象
     * @return boolean
     * @date 2021/4/21 9:26
     * @author ChenYongJia
     * @version 1.0
     */
    public boolean delUserInfo(List<SysUser> sysUser) {
        log.info("进入 SysUserManager 逻辑删除用户信息，参数 sysUserId：{}", JSONObject.toJSONString(sysUser));

        UserInfoDTO userInfoDTO = UserContext.get();
        SysUserRole sysUserRole = new SysUserRole();
        sysUser.stream().forEach(item -> {
            sysUserRole.setSysUserId(userInfoDTO.getSysUserId());
            if (!IsEmptyUtils.isEmpty(sysUserRoleService.selectSysUserRoleList(sysUserRole))) {
                item.setDelFlag(1);
                item.setUpdateTime(LocalDateTime.now());
                item.setUpdateUserId(userInfoDTO.getSysUserId());
            } else {
                log.error("出现错误：方法执行失败失败，当前用户绑定有相关角色请仔细检查并移除后尝试删除！");
                throw new BizException(ResultCode.ERROR);
            }
        });
        return iTbSysUserService.updateBatchById(sysUser);
    }

    /**
     * 根据系统用户表用户名称查询用户信息
     *
     * @param sysUserName 该名称需保证唯一性
     * @return com.dream.DreamChardonnay.model.system.SysUser
     * @date 2021/4/13 10:02
     * @author ChenYongJia
     * @version 1.0
     */
    public SysUser selectByUserName(String sysUserName) {
        log.info("进入 SysUserManager 根据用户名称查询用户信息方法，传入参数为：{}", sysUserName);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        // 未被锁定的用户
        // wrapper.eq(SysUser::getSysUserIsLock, UserGolEnum.IS_FALSE);
        // 未被删除的用户
        wrapper.eq(SysUser::getDelFlag, UserGolEnum.IS_FALSE);
        // 判断置入查询条件
        if (!IsEmptyUtils.isEmpty(sysUserName)) {
            wrapper.eq(SysUser::getUsername, sysUserName);
        } else {
            throw new BizException(ResultCode.DATA_IS_WRONG);
        }

        return iTbSysUserService.getOne(wrapper);
    }

    /**
     * 修改用户相关信息--（含登录所需修改）
     *
     * @param sysUser 用户对象
     * @return com.dream.DreamChardonnay.constant.model.Response
     * @date 2021/4/13 10:03
     * @author ChenYongJia
     * @version 1.0
     */
    public boolean updateSysUser(SysUser sysUser) {
        log.info("进入 SysUserManager 修改用户相关信息，传入参数为：{}", JSONObject.toJSONString(sysUser));
        UserInfoDTO userInfoDTO = UserContext.get();

        if (IsEmptyUtils.isEmpty(userInfoDTO)) {
            // 后台自动计算年龄
            if (!IsEmptyUtils.isEmpty(sysUser.getSysUserBirthday())) {
                sysUser.setSysUserAge(AgeUtils.getCurrentAge(sysUser.getSysUserBirthday()));
            }

            sysUser.setUpdateTime(LocalDateTime.now());
            return iTbSysUserService.updateById(sysUser);
        } else {
            // 后台自动计算年龄
            if (!IsEmptyUtils.isEmpty(sysUser.getSysUserBirthday())) {
                sysUser.setSysUserAge(AgeUtils.getCurrentAge(sysUser.getSysUserBirthday()));
            }

            sysUser.setUpdateTime(LocalDateTime.now());
            sysUser.setUpdateUserId(userInfoDTO.getSysUserId());
            return iTbSysUserService.updateById(sysUser);
        }
    }

    /**
     * 修改用户相关信息--（不含登录所需修改）
     *
     * @param sysUser 用户对象
     * @return com.dream.DreamChardonnay.constant.model.Response
     * @date 2021/4/13 10:03
     * @author ChenYongJia
     * @version 1.0
     */
    public boolean updateSysUserCloud(SysUser sysUser) {
        log.info("进入 SysUserManager 修改用户相关信息，传入参数为：{}", JSONObject.toJSONString(sysUser));

        UserInfoDTO userInfoDTO = UserContext.get();
        /*if (!IsEmptyUtils.isEmpty(this.selectByUserName(sysUser.getSysUsername()))) {
            log.error("用户名已存在，请重新填写表单后提交");
            throw new BizException(ResultCode.USER_HAS_EXISTED);
        }*/

        if (IsEmptyUtils.isEmpty(userInfoDTO)) {
            // 后台自动计算年龄
            if (!IsEmptyUtils.isEmpty(sysUser.getSysUserBirthday())) {
                sysUser.setSysUserAge(AgeUtils.getCurrentAge(sysUser.getSysUserBirthday()));
            }

            sysUser.setUpdateTime(LocalDateTime.now());
            return iTbSysUserService.updateById(sysUser);
        } else {
            // 后台自动计算年龄
            if (!IsEmptyUtils.isEmpty(sysUser.getSysUserBirthday())) {
                sysUser.setSysUserAge(AgeUtils.getCurrentAge(sysUser.getSysUserBirthday()));
            }

            sysUser.setUpdateTime(LocalDateTime.now());
            sysUser.setUpdateUserId(userInfoDTO.getSysUserId());
            return iTbSysUserService.updateById(sysUser);
        }
    }

    /**
     * 根据用户id查询用户
     *
     * @param sysUserId 用户id
     * @return com.dream.DreamChardonnay.model.system.SysUser
     * @date 2021/4/17 9:32
     * @author ChenYongJia
     * @version 1.0
     */
    public SysUser findBySysUserId(Long sysUserId) {
        log.info("进入 SysUserManager 根据用户id查询用户，传入参数为：{}", sysUserId);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getDelFlag, IsDeleteEnum.DIS_DELETE.getCode());
        wrapper.eq(SysUser::getDelFlag, sysUserId);
        return iTbSysUserService.getById(sysUserId);
    }

    /**
     * 查询系统用户信息
     *
     * @param queryRequest 入参参数
     * @return java.util.List<com.dream.DreamChardonnay.model.system.SysUser>
     * @date 2021/5/15 10:23
     * @author ChenYongJia
     * @version 1.0
     */
    public List<SysUser> findBySysUserInfo(SysUserQueryRequest queryRequest) {
        log.info("进入 SysUserManager 查询系统用户信息，参数 param：{}", queryRequest);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if (!IsEmptyUtils.isEmpty(queryRequest)) {
            // 用户id
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserId())) {
                wrapper.eq(SysUser::getDreamId, queryRequest.getSysUserId());
            }
            // 用户地址
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserAddress())) {
                wrapper.like(SysUser::getSysUserAddress, queryRequest.getSysUserAddress());
            }
            // 用户邮箱
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserEmail())) {
                wrapper.like(SysUser::getSysUserAddress, queryRequest.getSysUserEmail());
            }
            // 生日
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserBirthday())) {
                wrapper.eq(SysUser::getSysUserBirthday, queryRequest.getSysUserBirthday());
            }
            // 用户名称
            if (!IsEmptyUtils.isEmpty(queryRequest.getUsername())) {
                wrapper.like(SysUser::getUsername, queryRequest.getUsername());
            }
            // 用户是否锁定
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserIsLock())) {
                wrapper.eq(SysUser::getSysUserIsLock, queryRequest.getSysUserIsLock());
            }
            // 用户手机号
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserPhone())) {
                wrapper.like(SysUser::getSysUserPhone, queryRequest.getSysUserPhone());
            }
            // 用户性别
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserSex())) {
                wrapper.eq(SysUser::getSysUserSex, queryRequest.getSysUserSex());
            }
            // 部门
            if (!IsEmptyUtils.isEmpty(queryRequest.getSysUserInfoDepartmentId())) {
                wrapper.eq(SysUser::getSysUserInfoDepartmentId, queryRequest.getSysUserInfoDepartmentId());
            }
        }

        wrapper.orderByDesc(true, SysUser::getCreateTime);

        return iTbSysUserService.list(wrapper);
    }

}
